package com.alibaba.sample.petstore.dal.dao.cached;

import java.util.List;
import java.util.Map;

import com.alibaba.sample.petstore.dal.dao.ItemDao;
import com.alibaba.sample.petstore.dal.dataobject.Item;
import com.alibaba.sample.petstore.dal.dataobject.Order;

public class CachedItemDao extends AbstractCachedDao<ItemDao> implements ItemDao {
    private final Map<String, Item> itemsById = createCache();
    private final Map<String, List> itemListsByProductId = createCache();
    private final Map<String, Boolean> itemsInStock = createCache();

    public CachedItemDao(ItemDao backingDao) {
        super(backingDao);
    }

    public Item getItemById(String itemId) {
        Item item = itemsById.get(itemId);

        if (item == null) {
            item = backingDao.getItemById(itemId);
            itemsById.put(itemId, item);
        }

        return item;
    }

    public List getItemListByProductId(String productId) {
        List itemList = itemListsByProductId.get(productId);

        if (itemList == null) {
            itemList = backingDao.getItemListByProductId(productId);
            itemListsByProductId.put(productId, itemList);
        }

        return itemList;
    }

    public boolean isItemInStock(String itemId) {
        Boolean itemInStock = itemsInStock.get(itemId);

        if (itemInStock == null) {
            itemInStock = backingDao.isItemInStock(itemId);
            itemsInStock.put(itemId, itemInStock);
        }

        return itemInStock;
    }

    public void updateQuantity(Order order) {
        backingDao.updateQuantity(order);
    }
}
